import React, { useState } from 'react';
import { Button, Input, List, message, Card, Collapse, Typography, Space } from 'antd';
import { SearchOutlined, RobotOutlined, FileTextOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import { searchDocuments } from '../services/api';

const { Panel } = Collapse;
const { Title, Text } = Typography;

const ChatInterface: React.FC = () => {
  const [query, setQuery] = useState('');
  const [answer, setAnswer] = useState('');
  const [results, setResults] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  const handleSearch = async () => {
    if (!query.trim()) {
      message.warning('请输入检索内容');
      return;
    }
    setLoading(true);
    setAnswer('');
    setResults([]);
    try {
      const data = await searchDocuments(query);
      setAnswer(data.answer || '');
      const validDocuments = (data.relevantDocuments || []).filter((doc: any) => doc && doc.source && doc.content);
      setResults(validDocuments);
    } catch (error) {
      console.error('Search error:', error);
      message.error('检索失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: '900px', margin: '0 auto' }}>
      <div style={{ textAlign: 'center', marginBottom: '40px' }}>
        <Title level={2} style={{ color: '#1890ff', marginBottom: '8px' }}>
          <SearchOutlined /> 智能知识检索
        </Title>
        <Text type="secondary">基于向量数据库的智能文档检索系统</Text>
      </div>

      <Card 
        style={{ 
          marginBottom: '30px', 
          borderRadius: '12px',
          boxShadow: '0 4px 20px rgba(0, 0, 0, 0.08)'
        }}
        bodyStyle={{ padding: '30px' }}
      >
        <Input.Search
          placeholder="请输入您要查询的知识内容..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onSearch={handleSearch}
          enterButton={
            <Button 
              type="primary" 
              loading={loading}
              icon={<SearchOutlined />}
              size="large"
            >
              智能检索
            </Button>
          }
          size="large"
          style={{ 
            marginBottom: '0', 
            width: '100%',
            borderRadius: '8px'
          }}
        />
      </Card>
      
      {answer && (
        <Card 
          title={
            <Space>
              <RobotOutlined style={{ color: '#52c41a' }} />
              <span>AI智能回答</span>
            </Space>
          }
          style={{ 
            marginBottom: '30px', 
            borderRadius: '12px',
            border: '1px solid #e8f4fd',
            boxShadow: '0 4px 20px rgba(0, 0, 0, 0.06)'
          }}
          styles={{ 
            header: { 
              backgroundColor: '#f6ffed', 
              borderBottom: '1px solid #b7eb8f',
              borderRadius: '12px 12px 0 0'
            } 
          }}
        >
          <div style={{ 
            fontSize: '16px', 
            lineHeight: '1.8',
            color: '#333'
          }}>
            <ReactMarkdown>{answer}</ReactMarkdown>
          </div>
        </Card>
      )}
      
      {results.length > 0 && (
        <Collapse 
          defaultActiveKey={['1']}
          style={{ 
            marginBottom: '20px',
            borderRadius: '12px'
          }}
        >
          <Panel 
            header={
              <Space>
                <FileTextOutlined style={{ color: '#1890ff' }} />
                <span>相关文档 ({results.length} 个)</span>
              </Space>
            }
            key="1"
          >
            <List
              dataSource={results}
              renderItem={(item, index) => (
                <List.Item
                  style={{ 
                    border: '1px solid #f0f0f0', 
                    marginBottom: '12px', 
                    padding: '20px',
                    borderRadius: '8px',
                    backgroundColor: index % 2 === 0 ? '#fafafa' : '#fff',
                    transition: 'all 0.3s ease',
                    cursor: 'pointer'
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.transform = 'translateY(-2px)';
                    e.currentTarget.style.boxShadow = '0 6px 24px rgba(0, 0, 0, 0.12)';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.transform = 'translateY(0)';
                    e.currentTarget.style.boxShadow = 'none';
                  }}
                >
                  <List.Item.Meta
                    title={
                      <Space>
                        <FileTextOutlined style={{ color: '#1890ff', fontSize: '16px' }} />
                        <span style={{ 
                          fontWeight: '600', 
                          fontSize: '16px',
                          color: '#1890ff'
                        }}>
                          {item.source}
                        </span>
                      </Space>
                    }
                    description={
                      <div style={{ 
                        color: '#666', 
                        fontSize: '14px',
                        lineHeight: '1.6',
                        marginTop: '8px'
                      }}>
                        {item.content}
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </Panel>
        </Collapse>
      )}
      

    </div>
  );
};

export default ChatInterface;
